﻿using System.Diagnostics;
using Testing.Helpers.Assertion;

namespace Testing.Helpers.Processes
{
    /// <summary>
    /// Helpers for run application.
    /// </summary>
    public static class AppRunner
    {
        /// <summary>
        /// Launches the application.
        /// </summary>
        /// <param name="appPath">Full path to application exe file.</param>
        /// <param name="timeout">Launch application timeout.</param>
        /// <returns>Launched application process.</returns>
        public static Process RunApplication(string appPath, int timeout)
        {
            Process p = Process.Start(appPath);
            if (p == null)
            {
                throw new TestExecutionException("Failed to start application - " + appPath); 
            }
            bool result = p.WaitForInputIdle(timeout);
            if (!result)
            {
                throw new TestExecutionException("Failed to start application - " + appPath + " - during timeout " + timeout + " ms.");
            }
            return p;
        }

        /// <summary>
        /// Close all running applications by the name of the process.
        /// </summary>
        /// <param name="appProcessName">Application process name.</param>
        public static void CloseApplication(string appProcessName)
        {
            foreach (Process process in Process.GetProcessesByName(appProcessName))
            {
                process.Kill();
            }
        }

        /// <summary>
        /// Checks that the application is running.
        /// </summary>
        /// <param name="appProcessName">Application process name.</param>
        /// <returns>True if application is running.</returns>
        public static bool CheckAppIsRunning(string appProcessName)
        {
            return (Process.GetProcessesByName(appProcessName).Length > 0);
        }
    }
}
